<?php

namespace app\api\logic;

use app\common\exception\BusinessException;
use app\common\helper\JwtHelper;
use app\common\model\AgentRelation;
use app\common\model\User as UserModel;
use app\common\model\UserAgentRecord;
use app\common\service\UserService;
use app\common\service\WxService;
use think\facade\Db;

class WxLoginLogic
{
    /**
     * invoke
     * @param array $params
     * @return array
     * @throws BusinessException
     */
    public function invoke(array $params)
    {
        // 提取参数
        $wxCode = $params['wx_code'];
        $mobileCode = $params['mobile_code'];
        $appId = getAppId();

        // 查询微信手机号码
        $wx = new WxService();
        $wx->setAppId($appId);
        $mobile = $wx->getUserPhoneNumber($mobileCode);
        if (!$mobile) {
            throw new BusinessException('获取手机号码失败');
        }

        // 查询微信信息
        $wxInfo = $wx->getUserInfo($wxCode, '', '');
        $openid = $wxInfo['openid'] ?? '';
        if (!$openid) {
            throw new BusinessException('获取微信Openid信息失败');
        }
        $unionid = $wxInfo['unionid'] ?? '';

        // 开始登录
        $userId = $this->loginByOldWx($appId, $mobile, $openid, $unionid);
        if (!$userId) {
            $userId = $this->registerByWx($appId, $mobile, $openid, $unionid);
        }

        // 登录积分
        app(ScoreActivity::class)->initConfig($appId)->send($userId, 2);

        // 生成Token
        $token = JwtHelper::create($userId, config('mcp.tokenExpire'));

        // 返回用户信息
        $userInfo = app(UserService::class)->getUserById($userId);
        if (!$userInfo) {
            throw new BusinessException('用户数据异常');
        }
        $userInfo['token'] = $token;
        return $userInfo;
    }

    /**
     * registerByWx
     * @throws BusinessException
     */
    private function registerByWx($appId, $mobile, $openid, $unionid)
    {
        // 创建用户
        $time = time();
        $saveData = [
            'nickname' => '没有起名字的同学',
            'username' => $openid,
            'avatar' => getRandAvatar(),
            'openid' => $openid,
            'unionid' => $unionid,
            'mobile' => $mobile,
            'status' => 1,
            'app_id' => $appId,
            'create_time' => $time,
            'update_time' => $time,
        ];

        // 查询上级
        $userAgentRecord = new UserAgentRecord();
        $saveData['agent_id'] = $userAgentRecord->getMyAgentIdByOpenid($appId, $openid);

        // 创建用户
        $userId = app(UserModel::class)->insert($saveData, true);
        if (!$userId) {
            throw new BusinessException('创建用户失败');
        }

        // 保存分销关系
        if ($saveData['agent_id']) {
            $agentRelation = new AgentRelation();
            $agentRelation->add($userId, $saveData['agent_id']);
        }

        // 返回
        return $userId;
    }

    /**
     * loginByOldWx
     * @param $mobile
     * @param $openid
     * @param $unionid
     * @return int
     * @throws
     */
    private function loginByOldWx($appId, $mobile, $openid, $unionid): int
    {
        // 01.检查微信用户是否存在
        $userService = new UserService();
        $info = $userService->getUserByOpenid($appId, $openid);
        if (!$info) {
            return 0;
        }

        // 02.检查微信用户是否禁用
        if ($info['status'] != 1) {
            throw new BusinessException('账户已停用，请联系客服');
        }

        // 03.更新用户数据，填充unionid和mobile
        $saveData = ['update_time' => time()];
        if ($unionid && empty($info['unionid'])) {
            $saveData['unionid'] = $unionid;
        }
        if ($mobile && empty($info['mobile']) && !$userService->checkMobileExist($appId, $mobile)) {
            $saveData['mobile'] = $mobile;
        }
        $userService->setUserInfoById($info['id'], $saveData);

        // 返回
        return $info['id'];
    }
}